package main

import (
	"bytes"
	"crypto/des"
	"encoding/binary"
	"errors"
	"fmt"
	"os"
)

func ReadFile() []byte {
	outputFile, err := os.OpenFile("netdata", os.O_RDONLY, 0666)
	if err != nil {
		fmt.Println(err)
	}
	var filebuf bytes.Buffer
	_, err = filebuf.ReadFrom(outputFile)
	if err != nil {
		fmt.Println(err)
	}
	return filebuf.Bytes()[3:]
}

var TripleDesSecKey = []byte{95, 27, 5, 20, 131, 4, 8, 88,
	0, 0, 0, 0, 0, 0, 0, 0,
	0, 0, 0, 0, 0, 0, 0, 0}
var DesSecKey = []byte{95, 27, 5, 20, 131, 4, 8, 88}

func CalculateDesKey() []byte {
	var deckey = [1]uint64{0x0004312D}
	var decBytes bytes.Buffer
	for idx := 0; idx < len(deckey); idx++ {
		tmp := make([]byte, 8)
		binary.LittleEndian.PutUint64(tmp, deckey[idx])
		decBytes.Write(tmp)
	}
	return decBytes.Bytes()
}

func main() {
	SafeDevice := []byte{206, 241, 85, 181, 217, 71, 213, 44}
	Authorize := []byte{25, 247, 10, 162, 47, 105, 93, 92}

	//block, err := des.NewTripleDESCipher(TripleDesSecKey)
	block, err := des.NewCipher(DesSecKey)
	if err != nil {
		fmt.Println(err)
	}

	originAuthorize := make([]byte, 8)
	block.Decrypt(originAuthorize, Authorize)
	fmt.Printf("%v\n", originAuthorize)

	originSafeDevice := make([]byte, 8)
	block.Decrypt(originSafeDevice, SafeDevice)
	fmt.Printf("%v\n", originSafeDevice)
}

//[golang ECB 3DES Decrypt]
// func TripleEcbDesDecrypt(crypted, key []byte) ([]byte, error) {
// 	tkey := make([]byte, 24, 24)
// 	copy(tkey, key)
// 	k1 := tkey[:8]
// 	//k2 := tkey[8:16]
// 	//k3 := tkey[16:]
// 	//buf1, err := decrypt(crypted, k3)
// 	buf1, err := decrypt(crypted, k1)
// 	if err != nil {
// 		return nil, err
// 	}
// 	//buf2, err := encrypt(buf1, k2)
// 	// buf2, err := encrypt(buf1, k1)
// 	// if err != nil {
// 	// 	return nil, err
// 	// }
// 	// out, err := decrypt(buf2, k1)
// 	// if err != nil {
// 	// 	return nil, err
// 	// }
// 	// out = ZeroUnPadding(out)
// 	return out, nil
// }

//Des解密
func decrypt(crypted, key []byte) ([]byte, error) {
	if len(crypted) < 1 || len(key) < 1 {
		return nil, errors.New("wrong data or key")
	}
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, err
	}
	out := make([]byte, len(crypted))
	dst := out
	bs := block.BlockSize()
	if len(crypted)%bs != 0 {
		return nil, errors.New("wrong crypted size")
	}

	for len(crypted) > 0 {
		block.Decrypt(dst, crypted[:bs])
		crypted = crypted[bs:]
		dst = dst[bs:]
	}

	return out, nil
}

func ZeroUnPadding(origData []byte) []byte {
	return bytes.TrimFunc(origData,
		func(r rune) bool {
			return r == rune(0)
		})
}

func ZeroPadding(ciphertext []byte, blockSize int) ([]byte, int) {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := make([]byte, blockSize)
	copy(padtext[:], ciphertext)
	//padtext[7] = byte(padding)
	return padtext, padding
}
